import WfForm from './public/interface';
import * as InputUtil from './public/inputUtil';

let table = "";
let mainMap = "";
let detailMap = "";
let dtRow = "";
let tabsCount = "";
let tabsRow = "";
let mainEc = new Map();
let detailEc = new Map();
let store = "";
let _WfForm = "";

// 获取元素的值
function getText(cell, attrs, fieldmark) {
    let text = "";
    let fieldid = "0";
    let cellTd;
    if (cell) {
        cellTd = $(cell);
        fieldmark = cellTd.find("[data-fieldmark*=field]").attr("data-fieldmark");
        if (!fieldmark && (cell.className.includes("etype_13") || cell.className.includes("etype_17"))) {
            let arr = [];
            for (let i in store.cellInfo) {
                arr.push(i);
            }
            for (let mark of arr) {
                if (/mc_\d_\d_\d_nodemark/.test(mark)) {
                    text += store.cellInfo[mark];
                }
            }
            if (cellTd.find("img").size() > 0) {
                let imgs = Array.from(cellTd.find("img"));
                for (let img of imgs) {
                    let base64image = getBase64Image(img);
                    text += base64image + "&&";
                }
            }
            attrs.set("text", text.replace(/\n/g, ""));
            return;
        } else if (fieldmark === undefined) {
            text += cellTd[0].innerText;
            attrs.set("text", text);
            return;
        }
        if (!cellTd.find("[data-fieldmark*=field]").is(":visible")) {
            return;
        }
    }
    if (/field\d+_\d+/.test(fieldmark)) {
        fieldid = fieldmark.substring(5, fieldmark.indexOf("_"));
    } else {
        fieldid = fieldmark.substring(5);
    }
    const fieldAttr = WfForm.getFieldInfo(fieldid);
    const { htmltype,detailtype } = fieldAttr;
    const fieldValue = WfForm.getFieldValue(fieldmark);

    // 可编辑的单行文本
    if(fieldid < 0){
        if(fieldid === "-1" || fieldid === "-9"){
            text = fieldValue;
        }else if(fieldid === "-2"){
            if (fieldValue === "0") {
                text += "正常";
            } else if (fieldValue === "1") {
                text += "重要";
            } else {
                text += "紧急";
            }
        }else{
            text = "";
        }
    }else if (htmltype === 1) {
        if (detailtype === 4) {
            text += fieldValue;
            text += "<br>";
            text += InputUtil.convertAmountChinese(fieldValue);
        } else {
            if (cellTd && cellTd.find("table[class*=fintable]").size() > 0) {
                // 财务表头（每一位数字之前补一个 | ）
                let finborder = Array.from(cellTd.find("td.finborder"));
                for (let fin of finborder) {
                    if ($(fin).text() === "") {
                        text += " ";
                    }
                    text += $(fin).text() + "|";
                }
                text = text.substring(0, text.lastIndexOf("|"));
            } else {
                text += fieldValue;
            }
        }
    } else if (htmltype === 2) {
        let img_text = [];
        if (cellTd && cellTd.find("img").size() > 0) {
            let imgs = Array.from(cellTd.find("img"));
            for (let img of imgs) {
                let base64image = getBase64Image(img);
                img_text.push(base64image);
            }
        }
        let arr_text = _WfForm.getFieldValue(fieldmark).split(/<img.[^<]+>/);
        for (let i=0; i<arr_text.length; i++) {
            text += arr_text[i];
            if (i < img_text.length) {
                text += img_text[i];
            }
        }
        // 浏览按钮
    } else if (htmltype === 3) {
        if (detailtype === 2 || detailtype === 19) { // 日期与时间
            text += _WfForm.getFieldValue(fieldmark);
        } else {
            text += _WfForm.getBrowserShowName(fieldmark);
            text = text.replace(/,/g, " ");
        }
    } else if (htmltype === 4) {
        let selected = _WfForm.getFieldValue(fieldmark);
        selected = selected === "" ? "-1" : selected;
        text += Number(selected) === 1 ? "☑" : "☐";
    } else if (htmltype === 5) {
        let selected = _WfForm.getFieldValue(fieldmark);
        selected = selected === "" ? "-1" : selected;
        if (detailtype === 1) { // select
            text += _WfForm.getSelectShowName(fieldmark);
        } else if (detailtype === 2) { // 多个checkbox
            let itemlist = _WfForm.getFieldInfo(fieldid).selectattr.selectitemlist;
            for (let item of itemlist) {
                text += selected.indexOf(item.selectvalue) > -1 ? "☑" : "☐";
                text += item.selectname;
            }
        } else if (detailtype === 3) { // radio
            let itemlist = _WfForm.getFieldInfo(fieldid).selectattr.selectitemlist;
            for (let item of itemlist) {
                text += Number(selected) === item.selectvalue ? "●" : "○";
                text += item.selectname;
            }
        }
        // 附件/图片上传
    } else if (htmltype === 6) {
        if (detailtype === 1) {
            // 附件上传
            let files = mobx.toJS(_WfForm.getFieldObj(fieldmark)).specialobj.filedatas;
            for (let file of files) {
                text += file.filename + "<br/>";
            }
        } else if (detailtype === 2) {
            if (cellTd) {
                let imgs = Array.from(cellTd.find("img"));
                for (let img of imgs) {
                    let base64image = getBase64Image(img);
                    text += base64image + "&&";
                }
            }
        }
    } else if (htmltype === 7) {
        if (detailtype === 1) {
            if ("" !== _WfForm.getFieldInfo(fieldid).specialattr.linkaddress) {
                text += _WfForm.getFieldInfo(fieldid).specialattr.displayname + "@HYPERLINK@" +  _WfForm.getFieldInfo(fieldid).specialattr.linkaddress;
            }
        } else if (detailtype === 2) {
            // 描述性文字
            text += _WfForm.getFieldInfo(fieldid).specialattr.descriptivetext;
        }
    } else if (htmltype === 9) {
        if (detailtype === 1) {
            // 位置字段
            let specialobj = Array.from(store.mainData.get(fieldmark).specialobj);
            for (let obj of specialobj) {
                text += obj.flowNum + "    ";
                let locationlist = Array.from(obj.locationList);
                for (let location of locationlist) {
                    text += location.nodeName + "    ";
                    text += location.userName + "    ";
                    text += location.time + "    ";
                    text += location.address + "    ";
                }
                text += "\n";
            }
        }
    }
    if (text.endsWith("<br>")) {
        text = text.substring(0, text.lastIndexOf("<br>"));
    }
    attrs.set("text", text);
}

// 解析明细表
function detailTableAnalysis(element, detailId) {
    let rowCount = _WfForm.getDetailRowCount("detail_" + detailId);
    let fieldMap = new Map(Object.entries(WfForm.getLayoutStore().detailMap.get("detail_" + detailId).fieldInfo));
    let fieldNum = fieldMap.size;
    let colHeads = Array(fieldNum + 1);
    const controlWidthObj = jQuery(element).find("tr.detailControlWidth");
    for (let i = 1; i <= fieldNum + 1; i++) {
        colHeads[i] = controlWidthObj.find("td:eq("+i+")").width();
    }
    let rowHeadnum =detailEc.get("rowheads").size;
    let edtitleinrow = Number(store.dataJson.etables["detail_" + detailId].edtitleinrow);//明细表头所在行数
    let flag = true;
    for (let headrow=0;headrow<edtitleinrow;headrow++){
        let coloumn = new Map();
        for (let col = 1; col <= fieldNum + 1; col++) {
            let attrs = new Map();
            let id = headrow + "," + col;
            let col0id = headrow  + ",0";  //第一列id
            try {
                attrs = new Map(Object.entries(detailEc.get(id)));
                attrs.set("width", colHeads[col]);
                attrs.set("height", detailEc.get("rowheads").get("row_"+headrow));
            } catch(e) { }

            if (detailEc.get(col0id)&&detailEc.get(col0id).etype ==10){
                flag = false;
            }
            if(detailEc.get(id)){
                if (detailEc.get(id).etype==10) { //复制粘贴行
                    flag = false;
                }
                attrs.set("text", detailEc.get(id).evalue);
            }
            coloumn.set("" + (col - 1), attrs);
        }

        if (!flag){
            flag = true;
        }else {
            detailMap.set("" + dtRow, coloumn);
            dtRow++;
        }


    }
    let datarow = edtitleinrow+1;  //数据的第一行
    for (let row = edtitleinrow; row <(edtitleinrow+rowCount); row++) {
        let coloumn = new Map();
        for (let col = 1; col <= fieldNum + 1; col++) {
            let attrs = new Map();
            let id = datarow + "," + col;
            try {
                attrs = new Map(Object.entries(detailEc.get(id)));
                attrs.set("width", colHeads[col]);
                attrs.set("height", detailEc.get("rowheads").get("row_"+datarow));
            } catch (e) { }
            if (col == 1) {
                attrs.set("text", (row-edtitleinrow + 1) + "");
            } else {
                if (detailEc.get(datarow+"," + col)) {
                    getText(false, attrs, "field" + detailEc.get(datarow+"," + col).field + "_" + (row-edtitleinrow));
                }
            }
            coloumn.set("" + (col - 1), attrs);
        }

        detailMap.set("" + dtRow, coloumn);
        dtRow++;
    }

    //表尾后的行 （合计）
    let edtailinrow =  Number(store.dataJson.etables["detail_" + detailId].edtailinrow);//明细表尾所在行数
    for (let row =(edtailinrow+1);row <rowHeadnum; row++ ){
        let coloumn = new Map();
        let co11value = "";
        for (let col = 1; col <= fieldNum + 1; col++) {
            let attrs = new Map();
            let id = row + "," + col;
            try {
                attrs = new Map(Object.entries(detailEc.get(id)));
                attrs.set("width", colHeads[col]);
                attrs.set("height", detailEc.get("rowheads").get("row_"+row));
                let colspan = Number(detailEc.get(id).colspan);
                if(col==0&&colspan>1){//第一列colspan特殊处理下
                    attrs.set("colspan", colspan-1);
                }
            } catch (e) { }

            if (detailEc.get(id)) {
                if (col==1){  //如果序号列也有数据 那把选择列数据合并到序号列
                    co11value = detailEc.get(id).evalue;
                }
                if (detailEc.get(id).etype==19) { //合计数据
                    //detail_1_5_2
                    let sumtd = "detail_"+detailId+"_"+(row) +"_"+col;
                    const sumfieldtd = jQuery(element).find("td."+sumtd).find("span").text();
                    attrs.set("text",sumfieldtd);
                }else{
                    attrs.set("text", detailEc.get(id).evalue);
                }
            }
            coloumn.set("" + (col - 1), attrs);
        }

        //选择列有value的情况
        let id0 = row + ",0" ;
        let attrs0 = new Map();
        try {
            let ec0 = detailEc.get(id0);
            let colspan = Number(ec0.colspan);
            if(colspan>1){//第一列colspan特殊处理下
                ec0['colspan'] = colspan-1;
            }
            ec0['id'] = (edtailinrow+1) + ",1" ;
            attrs0 = new Map(Object.entries(ec0));
            attrs0 = new Map(Object.set("width", colHeads[0]));
            attrs0.set("height", detailEc.get("rowheads").get("row_"+(edtailinrow+1)));

        } catch (e) { }

        let col0value ="";
        if (detailEc.get(id0)) {
            if (detailEc.get(id0).etype==19) { //合计数据
                //detail_1_5_2
                // let sumtd = "detail_"+detailId+"_"+(edtailinrow+1) +"_"+col;
                // const sumfieldtd = jQuery(element).find("td."+sumtd).find("span").text();
                // attrs0.set("text",sumfieldtd);
            }else{
                if (detailEc.get(id0).evalue&&detailEc.get(id0).evalue!=""){
                    col0value = detailEc.get(id0).evalue;
                }
                if(co11value !=""&&col0value!=""){
                    co11value = " | "+co11value;
                }
                attrs0.set("text", col0value+""+co11value);
            }
        }
        if(col0value != ""){
            coloumn.set("0", attrs0);
        }


        detailMap.set("" + dtRow, coloumn);
        dtRow++;
    }
   // console.log("detailmap"+JSON.stringify(detailMap));
}



// 解析主表
function recursiveDFS(element) {
    if (element.tagName === "TABLE" && element.className === "excelDetailTable" && $(element).is(":visible")) {
        if (/oTable\d+_head/.test(element.id)) {
            return;
        }
        detailMap = new Map();
        let detailId = Number(element.id.replace("oTable", "")) + 1;
        if(isNaN(detailId)){
            return;
        }
        table.set("detail_" + detailId, detailMap);
        dtRow = 0;
        for (let td of store.dataJson.etables["detail_" + detailId].ec) {
            detailEc.set(td.id, td);
        }
        // let colheads = new Map(Object.entries(store.dataJson.etables["detail_" + detailId].colheads));
        let rowheads = new Map(Object.entries(store.dataJson.etables["detail_" + detailId].rowheads));
        // handleWidth(colheads);
        // detailEc.set("colheads", colheads);
        detailEc.set("rowheads", rowheads);
        detailTableAnalysis(element, detailId);
        return;
    }
    if (element.tagName === 'TR' && $(element).is(":visible")) { // 一行
        let coloumn = new Map();
        let coordinate = null;
        for (let j = 0; j < element.children.length; j++) {
            let cell = element.children[j];
            if (cell.tagName === "TD" && $(cell).is(":visible") && !(cell.className.includes("_hide_") || cell.className.includes("tab_"))) { // 一个单元格
                let attrs = new Map();
                let cellTd = $(cell);
                let classname = "";
                if (cellTd.attr("class") !== undefined && cellTd.attr("class") !== null && cellTd.attr("class").includes("etype")) {
                    classname = cellTd.attr("class").substring(0, cellTd.attr("class").indexOf("etype") - 1);
                }

                if (classname !== "") {
                    coordinate = classname.substring(7).split("_");
                    let id = coordinate[0] + "," + coordinate[1];
                    try {
                        attrs = new Map(Object.entries(mainEc.get(id)));
                        attrs.set("width", cellTd.css("width").replace("px", ""));
                        attrs.set("height", cellTd.css("height").replace("px", ""));
                        attrs.set("colspan", cellTd.attr("colspan"));
                        attrs.set("rowspan", cellTd.attr("rowspan")); 
                    } catch (e) { }
                    if (undefined !== mainEc.get(id) && undefined !== mainEc.get(id).mcpoint) {
                        attrs.set("mcpoint", store.dataJson.etables[mainEc.get(id).mcpoint].ec);
                    }
                } else {
                    if (cellTd.children().length > 0 ) {
                        continue;
                    }
                    attrs.set("colspan", cellTd.attr("colspan"));
                    attrs.set("rowspan", cellTd.attr("rowspan"));
                    attrs.set("height", cellTd.css("height").substring(0, cellTd.css("height").indexOf("px")));
                    if (coloumn.size === 0) {
                        coloumn.set(j + "", attrs);
                        attrs.set("width", mainEc.get("colheads").get("col_" + j));
                    } else {
                        let key = Number(Array.from(coloumn.keys()).pop());
                        attrs.set("width", cellTd.css("width").replace("px", ""));
                        attrs.set("height", cellTd.css("height").replace("px", ""));
                        if (coloumn.get(key + "").get("colspan") === undefined) {
                            coloumn.set((key + 1) + "", attrs);
                        } else {
                            coloumn.set((key + Number(coloumn.get(key + "").get("colspan"))) + "", attrs);
                        }
                    }
                    continue;
                }
                getText(cell, attrs, "");
                let items = cellTd.find("table[class=excelDetailTable]");
                if (items.size() > 0) {
                    let id = 0;
                    for (let i = 0; i < items.size(); i++) {
                        if (/oTable\d+$/.test(items[i].id)) {
                            id = Number(items[i].id.replace("oTable", "")) + 1;
                            break;
                        }
                    }
                    attrs.set("text", "明细表" + id);
                    attrs.set("font-weight", "400");
                    attrs.set("link", "'明细表" + id + "'!A1");
                    attrs.set("height", "40");
                    coloumn.set(coordinate[1], attrs);
                    continue;
                }

                if (cellTd.find("table[class*=ViewForm]").size() > 0 && (cellTd.find("table[class*=ViewForm]").size() === cellTd.find("table").size())) {
                    attrs.set("text", "内部或外部链接");
                    attrs.set("font-weight", "400");
                    attrs.set("height", "40");
                }
                if (cellTd.attr("class").includes("etype_12")) {
                    tabsCount = cellTd.find("table.excelDetailTable").size();
                    tabsRow = Number(coordinate[0]);
                }
                coloumn.set(coordinate[1], attrs);
            }
        }
        if (coordinate !== null) {
            if (tabsRow !== 0 && Number(coordinate[0]) > tabsRow) {
                coordinate[0] = tabsCount - 1 + Number(coordinate[0]);
            }
            mainMap.set(coordinate[0], coloumn);
        }

    }
    for (let i = 0; i < element.children.length; i++) {
        recursiveDFS(element.children[i]);
    }
}

// map转为json
function mapToObject(table) {
    const out = Object.create(null);
    table.forEach((value, key) => {
        if (value instanceof Map) {
            out[key] = mapToObject(value);
        }
        else {
            out[key] = value;
        }
    });
    return out;
}

// 初始化
async function init() {
    table = new Map();
    mainMap = new Map();
    detailMap = new Map();
    dtRow = 0;
    tabsCount = 0;
    tabsRow = 0;
    table.set("maintable", mainMap);
    /*$(".prependImg").remove();
    let element = $($("div.wf-req-form")[0]).find("td");
    for (let i=0; i<element.size(); i++) {
        let url = $(element[i]).css("background-image");
        if (/url\(.+\)/.test(url)) {
            let base64 = await getCanvasBase64(url.replace("url(\"","").replace("\")", ""));
            let img = $("<img></img>").attr("src", base64).attr("class", "prependImg").css("display", "none");
            $(element[i]).prepend(img);
        }
    }*/
    if ($("#reqIframe").size() === 0) {
        _WfForm = WfForm;
        store = _WfForm.getLayoutStore();
    } else {
        _WfForm = document.getElementById("reqIframe").contentWindow.WfForm;
        store = _WfForm.getLayoutStore();
    }
    if (store.dataJson === undefined) {
        return;
    }
    for (let td of store.dataJson.etables.emaintable.ec) {
        mainEc.set(td.id, td);
    }
    mainEc.set("colheads", new Map(Object.entries(store.dataJson.etables.emaintable.colheads)));
    mainEc.set("rowheads", new Map(Object.entries(store.dataJson.etables.emaintable.rowheads)));
}

function getCanvasBase64(img) {
    let image = new Image();
    image.crossOrigin = '';
    image.src = img;
    let deferred = $.Deferred();
    if (img) {
        image.onload = function () {
            deferred.resolve(getBase64Image(image));
        };
        return deferred.promise();
    }
}

// get base64 url with a img object
function getBase64Image(img) {
    let c = document.createElement("canvas");
    c.width = img.naturalWidth;
    c.height = img.naturalHeight;
    let ctx = c.getContext("2d");
    ctx.drawImage(img, 0, 0, c.width, c.height);
    return c.toDataURL();
}


// 方法入口
export const getStyleJson = async () => {
    await init();
    let element = "";
    if ($("#reqIframe").size() === 0) {
        element = $(".wf-req-form")[0];
    } else {
        element = document.getElementById("reqIframe").contentWindow.document.getElementsByClassName("wf-req-form")[0];
    }
    recursiveDFS(element);
    for (let i = 1; i < tabsCount; i++) {
        let detailRowMap = new Map(table.get("maintable").get("" + tabsRow));
        table.get("maintable").set("" + (tabsRow + i), detailRowMap);
    }
    return JSON.stringify(mapToObject(table));
}
